package com.calvin.component;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.RoundRobinRule;
import com.netflix.loadbalancer.Server;

/**
 * 该类不能存放在主应用程序上下文的@ComponentScan所扫描的包中，否则该类中的配置信息将被所有的@RibbonClient共享。
 * 
 * @ClassName:RibbonRule
 * @Description:TODO(描述这个类的作用)
 * @author:Calvin.W
 * @date:2022年2月14日 上午9:20:53
 */
public class RibbonRule extends AbstractLoadBalancerRule {

	  /**
     * Randomly choose from all living servers
     */
    //@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE")
	
    
    int currentServer = 0;  //当前第几个服务
    int callServerNums = 0;//每个服务的调用次数
    
    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        }
        Server server = null;

        while (server == null) {
            if (Thread.interrupted()) {
                return null;
            }
            //获取可用服务
            List<Server> upList = lb.getReachableServers();
            //获取所有服务
            List<Server> allList = lb.getAllServers();
            

            int serverCount = allList.size();
            if (serverCount == 0) {
                return null;
            }

            
            if(callServerNums < 3) {
            	server = upList.get(currentServer);
            	callServerNums++;
            }else {
            	callServerNums = 0;
            	currentServer++;
            	if(currentServer >= upList.size()) {
            		currentServer = 0;
            	}
            	server = upList.get(currentServer);
            }
            

            //int index = chooseRandomInt(serverCount);
            //server = upList.get(index);

            if (server == null) {
                Thread.yield();
                continue;
            }

            if (server.isAlive()) {
                return (server);
            }

            // Shouldn't actually happen.. but must be transient or a bug.
            server = null;
            Thread.yield();
        }

        return server;

    }

    protected int chooseRandomInt(int serverCount) {
        return ThreadLocalRandom.current().nextInt(serverCount);
    }

	@Override
	public Server choose(Object key) {
		return choose(getLoadBalancer(), key);
	}

	@Override
	public void initWithNiwsConfig(IClientConfig clientConfig) {
		// TODO Auto-generated method stub
		
	}
}
